const acl = require("express-acl");

module.exports = ({ env, db }) => {
  const unlessPath = ["/login", "/init"].map(
    (el) => `${env.ROUTE_BASE_PATH}${el}`
  );
  const rules = db.get("rules").value();
  const menus = router.db.get("menus").value();

  // 根据叶子节点构建菜单树
  function treeMenusByLeafId(id, r = [id]) {
    const { pid } = menus.find((el) => el.id === id);
    if (pid !== 0) {
      const t = menus.find((el) => el.id === pid);
      r.push(t.id);
      treeMenusByLeafId(t.id, r);
    }
    return r;
  }
  /* --- */
  rules.forEach((el) => {
    // el.treeMenus = el.menus.reduce((arr, ell) => {
    //   return [...new Set(arr.concat(...treeMenusByLeafId(ell)))];
    // }, []);
    el.permissions = el.menus.map((id) => {
      const menus = router.db.get("menus").find({ id }).value();
      return menus.permission;
    });
  });
  /* --- */
  acl.config({
    rules,
    decodedObjectName: "auth",
  });
  return acl.authorize.unless({ path: unlessPath });
};
